﻿using System;
using System.Reflection;

namespace ParseExpression
{
    public class ParsedFunction
    {
        public ParsedFunction(string expression, int numVariables, MethodInfo methodInfo)
        {
            _method = methodInfo;
            Expression = expression;
            NumVariables = numVariables;
        }

        public double GetValue(double[] variables)
        {
            double result;

            try
            {
                if (NumVariables == 1)
                {
                    result = (double) _method.Invoke(null, new object[] {variables[0]});
                }
                else
                {
                    result = (double) _method.Invoke(null, new object[] {variables[0], variables[1]});
                }
            }
            catch (Exception)
            {
                result = Double.NaN;
            }
           
            return result;
        }

        public string Expression { get; private set; }

        public int NumVariables { get; private set; }

        private readonly MethodInfo _method;
    }
}
